<?php
namespace Framework;

class Config
{
    //创建静态私有的变量保存该类对象
    static private $instance;

    //防止使用new直接创建对象
    private function __construct(){}

    //防止使用clone克隆对象
    private function __clone(){}

    //超级配置数组
    protected $config = [];

    /**
     * 配置文件目录
     * @var string
     */
    protected $path;

    protected $files = [];

    static public function getInstance()
    {
        //判断$instance是否是Config的对象，不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取一级配置
     * @access protected
     * @param  string $name 一级配置名
     * @return array
     */
    protected function pull(string $name): array
    {
        $name = strtolower($name);

        return $this->config[$name] ?? [];
    }

    public function load($name){
        $this->path = dirname( __DIR__) . DIRECTORY_SEPARATOR. 'config' . DIRECTORY_SEPARATOR;
        // echo $this->path;

        //标记该配置已经尝试加载过
        $this->files[] = $name;

        $file = $this->path. $name . '.php';
        if( is_file($file) ){
            $config = include_once $file;
            if( is_array($config) ){
                $this->set($config, $name);
            }
        }

        return $this->config;
    }

    public function get(string $name = null, $default = null){
        // 无参数时获取所有
        if (empty($name)) {
            return $this->config;
        }

        $nameArr    = explode('.', $name);
        $nameArr[0] = strtolower($nameArr[0]);


        //如果一级配置还未被加载，现在去加载
        if( !isset($this->files[$nameArr[0]]) ){
            $this->load($nameArr[0]);
        }

        //返回一级配置
        if (false === strpos($name, '.')) {
            return $this->pull($name);
        }


        $config  = $this->config;
        // 按.拆分成多维数组进行判断
        foreach ($nameArr as $val) {
            if (isset($config[$val])) {
                $config = $config[$val];
            } else {
                return $default;
            }
        }

        return $config;
    }

    /**
     * 设置配置参数 name为数组则为批量设置
     * @access public
     * @param  array  $config 配置参数
     * @param  string $name 配置名
     * @return array
     */
    public function set(array $config, string $name = null): array
    {
        if (!empty($name)) {
            if (isset($this->config[$name])) {
                $result = array_merge($this->config[$name], $config);
            } else {
                $result = $config;
            }

            $this->config[$name] = $result;
        } else {
            $result = $this->config = array_merge($this->config, array_change_key_case($config));
        }

        return $result;
    }

}